package com.own.component.common.util;

import lombok.Cleanup;
import lombok.extern.slf4j.Slf4j;
import org.yaml.snakeyaml.util.UriEncoder;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;

/**
 * HeaderMapUtil
 *
 * @author chenxueli
 * @date 2023-12-21 08:46:00
 */
@Slf4j
public class RequestUtil {

    /**
     * 获取请求中的header信息
     *
     * @param request 请求
     * @return header信息
     */
    public static Map<String, String> header(HttpServletRequest request) {
        return header(request, Function.identity());
    }

    /**
     * 获取请求中的header信息
     *
     * @param request 请求
     * @return header信息
     */
    public static Map<String, String> headerForDecode(HttpServletRequest request) {
        return header(request, UriEncoder::decode);
    }

    /**
     * 获取请求中的header信息
     *
     * @param request       请求
     * @param valueFunction 转换函数
     * @return header信息
     */
    public static Map<String, String> header(HttpServletRequest request, Function<String, String> valueFunction) {
        var headerNames = request.getHeaderNames();
        var map = new HashMap<String, String>();
        while (headerNames.hasMoreElements()) {
            try {
                var name = headerNames.nextElement();
                map.put(name, valueFunction.apply(request.getHeader(name)));
            } catch (Exception e) {
                log.info("获取header信息失败", e);
            }
        }
        return map;
    }

    /**
     * 获取请求中的cookie信息
     *
     * @param request 请求
     * @return cookie信息
     */
    public static Map<String, String> cookies(HttpServletRequest request) {
        var cookies = request.getCookies();
        var map = new HashMap<String, String>();
        for (var cookie : cookies) {
            map.put(cookie.getName(), cookie.getValue());
        }
        return map;
    }

    /**
     * 获取请求Body（需要注意当前的body数据只能读取一次）
     *
     * @param request 请求
     * @return 请求Body
     */
    public static String body(ServletRequest request) {
        try {
            var builder = new StringBuilder();
            @Cleanup
            var inputStream = request.getInputStream();
            @Cleanup
            var reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
            String line;
            while ((line = reader.readLine()) != null) {
                builder.append(line);
            }
            return builder.toString();
        } catch (IOException e) {
            return "";
        }
    }

}
